package com.solocredit.finance.ui.user.act

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.solocredit.finance.R
import com.solocredit.finance.databinding.ActMullaUserProfileBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.ProAct
import com.solocredit.finance.utils.DateUtils
import com.solocredit.finance.utils.dialog.TipsDialog
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.MullaCustomDataHelper
import com.solocredit.finance.weight.pickerview.builder.TimePickerBuilder
import com.solocredit.finance.weight.pickerview.listener.OnTimeSelectListener
import com.solocredit.finance.weight.pickerview.view.TimePickerView
import java.util.Calendar
import java.util.Date

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/15 19:40
 * @Annotation：用户简介
 */
class MullaUserProfileAct: ProAct() {
//    lateinit var binding: ActMullaUserProfileBinding
    private var _binding: ActMullaUserProfileBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    //出生日期选择
    private var pvStartDateView: TimePickerView? = null

    override fun getMullaRootView(): View {
        _binding = ActMullaUserProfileBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTextTitle(getString(R.string.user_profile))
        setMullaBackBtnRes(R.mipmap.mulla_back_black)
        setMullaRightBtnRes(R.mipmap.mulla_kefu_icon)
    }

    override fun initMullaListener() {
        //客服
        rootViewBinding.ivFun.setOnClickListener {
            showMullaKefuDialog("User Profile Page")
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"User Profile Page")
            _binding?.let {
                if (it.editName.isFocused){
                    it.editName.clearFocus()
                }
            }
        }
        rootViewBinding.ivLanguage.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LANGUAGE,"User Profile Page")
            showMullaLanguageDialog("User Profile Page", onSelectCallback = {
            })
        }

        _binding?.parentLayout?.setOnClickListener {
            _binding?.let {
                if (it.editName.isFocused){
                    it.editName.clearFocus()
                }
            }
        }

        //选择头像
        _binding?.avatarLayout?.setOnClickListener {
            _binding?.let {
                if (it.editName.isFocused){
                    it.editName.clearFocus()
                }
            }
            onIntent(MullaUserAvatarAct::class.java)
        }

        //昵称
        _binding?.editName?.setOnFocusChangeListener { v, hasFocus ->
            when(hasFocus){
                true -> {//获得焦点

                }
                else -> {//失去焦点
                    val userName = _binding?.editName?.text.toString().trim()
                    if (userName.isNotEmpty()){
                        MullaCustomDataHelper.saveMullaCustomUserNameAction(userName)
                    }
                }
            }
        }
        _binding?.editName?.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                _binding?.editName?.clearFocus()
                true
            }
            false
        }

        //选择生日(只能修改一次)
        _binding?.birthdayLayout?.setOnClickListener {
            _binding?.let {
                if (it.editName.isFocused){
                    it.editName.clearFocus()
                }
            }
            showMullaBirthdayDialog()
        }
    }

    override fun initMullaData() {
        showMullaUserInfo()

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.visibility = View.GONE
        } else {
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.addView(licenseView())
            _binding?.licenseLayout?.visibility = View.VISIBLE
        }
    }

    /**
     * 设置用户头像和昵称
     */
    @SuppressLint("SimpleDateFormat")
    private fun showMullaUserInfo(){
        _binding?.imgAvatar?.setImageResource(MullaCustomDataHelper.getMullaCustomUserAvatar())
        _binding?.editName?.setText(MullaCustomDataHelper.getMullaCustomUserName())

        //生日只能设置一次
        val birthday = MullaCustomDataHelper.getMullaCustomUserBirthday()
        if (birthday.isEmpty()){
            _binding?.imgEnable?.visibility = View.VISIBLE
            _binding?.birthdayLayout?.isEnabled = true
        } else {
            _binding?.imgEnable?.visibility = View.GONE
            _binding?.birthdayLayout?.isEnabled = false

            val showBirthday = DateUtils.getFormatTime(birthday.toLong() * 1000,"dd/MM/yyyy")
            _binding?.textBirthday?.text = showBirthday
        }
    }

    /**
     * 选择出生日期
     */
    private fun showMullaBirthdayDialog(){
        if(pvStartDateView == null){
            //时间可选范围18-100岁
            //当前日期
            val curtDate = Calendar.getInstance()
            val startDate = Calendar.getInstance()
            startDate.timeInMillis = curtDate.timeInMillis
            startDate.add(Calendar.YEAR,-100)

            val endDate = Calendar.getInstance()
            endDate.timeInMillis = curtDate.timeInMillis
            endDate.add(Calendar.YEAR,-18)

            pvStartDateView = TimePickerBuilder(this, object : OnTimeSelectListener {
                    override fun onTimeSelect(date: Date?, v: View?) {
                    }

                    @SuppressLint("SimpleDateFormat")
                    override fun onTimeSelectString(date: Date?, showDate: String?) {
                        showMullaConfirmDialog(date)
                    }
                })
                .setDate(endDate) //默认选中
                .setRangDate(startDate, endDate) //可选择时间范围
                .setLayoutRes(R.layout.dialog_mulla_birthday) { v ->
                    val ivClose = v.findViewById<ImageView>(R.id.ivClose)
                    ivClose.setOnClickListener {
                        pvStartDateView?.dismiss()
                    }
                    //确定
                    val btnDone = v.findViewById<TextView>(R.id.btnDone)
                    btnDone.setOnClickListener {
                        pvStartDateView?.returnData()
                        pvStartDateView?.dismiss()
                    }
                }
                .isDialog(true)
                .setContentTextSize(16)
                .setType(booleanArrayOf(true, true, true, false, false, false))
                .setLabel("", "", "", "", "", "")
                .setLineSpacingMultiplier(3f)
                .setTextXOffset(40, 40, 40, 40, 40, 40)
                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setTextColorCenter(Color.parseColor("#FF08252C")) //设置选中项文字颜色
                .setTextColorOut(Color.parseColor("#FF9CA8AB"))//默认颜色
                .setBgColor(Color.parseColor("#00000000"))
                .isAlphaGradient(true)
                .setItemVisibleCount(5)
                .isCyclic(true)
                .setDividerColor(ContextCompat.getColor(this, R.color.transparent))
                .build()
            val dialog = pvStartDateView?.dialog
            if (dialog != null){
                val dialogWindow = dialog.window
                if (dialogWindow != null) {
                    val params = dialogWindow.attributes
                    params.width = WindowManager.LayoutParams.MATCH_PARENT
                    params.height = WindowManager.LayoutParams.WRAP_CONTENT
                    dialogWindow.attributes = params
                    dialogWindow.setWindowAnimations(R.style.picker_view_slide_anim) //修改动画样式
                    dialogWindow.setGravity(Gravity.BOTTOM)
                    dialogWindow.setDimAmount(0.3f)
                }
            }
        }
        pvStartDateView?.show()
    }

    /**
     * 设置生日二次确认弹框
     */
    private fun showMullaConfirmDialog(date: Date?){
        date?.let {
            val showTipsText = getString(R.string.user_birthday_confirm_tips)
            val tipsDialog = TipsDialog(this,object : TipsDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.btnOk){
                        val value = DateUtils.getFormatTime(it.time,"dd/MM/yyyy")
                        _binding?.textBirthday?.text = value
                        MullaCustomDataHelper.saveMullaCustomUserBirthday("${it.time / 1000}")

                    }
                }
            })
            tipsDialog.setCancelable(true)
            tipsDialog.setCanceledOnTouchOutside(false)
            tipsDialog.show()
            tipsDialog.setTipsTitle(getString(R.string.tips))
            tipsDialog.setTips(showTipsText)
            tipsDialog.setBtnText(getString(R.string.btn_confirm))
        }
    }

    override fun onMullaEvent(event: MullaEventData) {
        when(event.eventType){
            MullaEventData.TYPE.MULLA_CUSTOM_DATA_REFRESHED -> {//自定义数据刷新完成
                //设置用户昵称和头像
                showMullaUserInfo()
            }
            else -> {

            }
        }
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_USER_PROFILE_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_USER_PROFILE_END)
    }
}